﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfAppDuplexClient.ServiceReference1;
using System.ServiceModel;
using System.Threading;

namespace WpfAppDuplexClient
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window, IMyDuplexServiceCallback
	{
		internal InstanceContext m_context;
		internal AutoResetEvent m_event;
		internal ServiceReference1.MyDuplexServiceClient m_client;
		WSDualHttpBinding m_binding;

		public MainWindow()
		{
			InitializeComponent();
			m_context = new InstanceContext(this);
			m_event = new AutoResetEvent(false);
			m_client = new MyDuplexServiceClient(m_context);
			m_binding = m_client.Endpoint.Binding as WSDualHttpBinding;


			this.Loaded += (send, arg) =>
			{
				ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
				{
					m_client.Open();
				}));
			};

			this.Closing += (send, arg) =>
			{
				if (m_client != null && m_client.State == CommunicationState.Opened)
				{
					this.Dispatcher.BeginInvoke(new Action(() =>
					{
						m_client.Leave(txtUserId.Text);
						m_client.Close();
					}));
				}
			};
		}

		private void btnJoin_Click(object sender, RoutedEventArgs e)
		{
			if (m_client != null)
			{
				m_client.Join(txtUserId.Text.Trim());
			}
		}

		private void btnLeave_Click(object sender, RoutedEventArgs e)
		{
			if (m_client != null)
				m_client.Leave(txtUserId.Text.Trim());
		}

		private void btnSendMess_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				if (txtMessage.Text.Trim().Length != 0)
				{
					m_client.SendMessage(txtUserId.Text, txtMessage.Text);
					txtMessage.Text = "";
				}
			}
			catch
			{
				string errormsg = "The id you have chosen is already in use ! Please enter a different chat name and join.";
				MessageBox.Show(errormsg, "Identitity Error", MessageBoxButton.OK, MessageBoxImage.Error);

				listMsgs.Items.Clear();
				InstanceContext context = new InstanceContext(this);
				m_client = new ServiceReference1.MyDuplexServiceClient(context);
			}
			finally
			{
				m_event.WaitOne();
			}
		}

		public void OnCallback(string message)
		{
			this.Dispatcher.BeginInvoke(new Action(() =>
			{
				listMsgs.Items.Add(message);
			}));

			m_event.Set();
		}
	}
}
